//
//  ZYCSelectAmPmDateView.m
//  ZDSC
//
//  Created by 张威 on 2021/11/6.
//

#import "ZYCSelectAmPmDateView.h"
#import "NSDate+BRPickerView.h"
#import "NSDateExtra.h"

#define kDateViewH 258
#define kPickViewH 218

@interface ZYCSelectAmPmDateView ()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic, strong) UIView *baseView;
@property (nonatomic, strong) UIView *dimView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, strong) NSArray *ampmArray;
@property (nonatomic, strong) NSArray *dateArray;

@property (nonatomic, assign) NSInteger minYear;
@property (nonatomic, assign) NSInteger maxYear;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@end

@implementation ZYCSelectAmPmDateView


#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.backgroundColor = [UIColor colorWithRed:1.00f green:1.00f blue:1.00f alpha:0.00f];
        [self setupUI];
        [self setupConstraint];
        self.ampmArray = [NSArray arrayWithObjects:@"上午",@"下午", nil];
        self.selectDate = [NSDate date];
        self.minYear =  [[self.dateFormatter stringFromDate:[NSDate date]] integerValue] - 1;
        self.maxYear = [[self.dateFormatter stringFromDate:[NSDate date]] integerValue] + 1;
        
        self.minLimitDate = [NSDate br_setYear:self.minYear month:1 day:1];
        self.maxLimitDate = [NSDate br_setYear:self.maxYear month:1 day:1];
        self.selectAMPM = @"上午";
        [self loadDate];
    
    }
    return self;
}

- (void)loadDate{
    dispatch_queue_t queue = dispatch_queue_create("zdtx", NULL);
    dispatch_async(queue, ^{
        NSInteger yearNum = 0;
        NSInteger monthNum = 0;
        NSInteger dayNum = 0;
        NSMutableArray *tempArr = [NSMutableArray array];
        for (NSInteger i = self.minLimitDate.br_year; i <= self.maxLimitDate.br_year; i++) {
            double start  = CFAbsoluteTimeGetCurrent();
            yearNum = i;
            NSInteger startMonth = 1;
            NSInteger endMonth = 12;
            if (yearNum == self.selectDate.br_year - 1) {
                startMonth = 12;
            }
            for (NSInteger i = startMonth; i <= endMonth; i++) {
                monthNum = i;
                NSInteger startDay = 1;
                NSInteger endDay = [NSDate br_getDaysInYear:yearNum month:monthNum];
                for (NSInteger i = startDay; i <= endDay; i++) {
                    dayNum = i;
                    [tempArr addObject: [NSString stringWithFormat:@"%ld年%.2ld月%.2ld日",(long)yearNum,(long)monthNum,(long)dayNum]];
                }
                double end  = CFAbsoluteTimeGetCurrent();
            }
            self.dateArray = [tempArr copy];
        }
        [self scrollToCurrentDateRow];
    });
}

#pragma mark - 滚动到当前日期
- (void)scrollToCurrentDateRow
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *str = [NSString stringWithFormat:@"%ld年%.2ld月%.2ld日",(long)self.selectDate.br_year,(long)self.selectDate.br_month,(long)self.selectDate.br_day];
        for (NSInteger i = 0; i < self.dateArray.count; i++) {
            if ([str isEqualToString:self.dateArray[i]]) {
                self.selectDateValue =  str;
                [self.pickView selectRow:i inComponent:0 animated:NO];
                [self.pickView reloadAllComponents];
            }
        }
        
    });
    
}

#pragma mark - UI及约束
- (void)setupUI{
    [self addSubview:self.dimView];
    [self addSubview:self.baseView];
    [self.baseView addSubview:self.cancelBtn];
    [self.baseView addSubview:self.confirmBtn];
    [self.baseView addSubview:self.pickView];
    [self.baseView addSubview:self.lineView];
    [self.baseView addSubview:self.titleLabel];
}

- (void)setupConstraint{
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.baseView.mas_top).offset(20);
        make.centerX.equalTo(self);
    }];
    [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self);
        make.top.equalTo(self.baseView.mas_top);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self);
        make.top.equalTo(self.baseView.mas_top);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
   
}

#pragma mark - UIPickerViewDelegate,UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSArray *rowsArr = [NSArray array];
    rowsArr = @[@(self.dateArray.count), @(self.ampmArray.count)];
    return [rowsArr[component] integerValue];
}


// 设置row字体，颜色
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc]init];
        pickerLabel.backgroundColor = [UIColor clearColor];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
    }
    // 给选择器上的label赋值
    [self setDateLabelText:pickerLabel component:component row:row];
    return pickerLabel;
}

- (void)setDateLabelText:(UILabel *)label component:(NSInteger)component row:(NSInteger)row
{
    if (component == 0) {
        label.text = [NSString stringWithFormat:@"%@", self.dateArray[row]];
    } else if (component == 1) {
        label.text = [NSString stringWithFormat:@"%@", self.ampmArray[row]];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.selectDateValue = _dateArray[row];
    }else if (component == 1){
        self.selectAMPM = _ampmArray[row];
    }

}
#pragma mark - 显示与隐藏
- (void)show{
    self.dimView.hidden = NO;
    self.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^{
        self.baseView.frame = CGRectMake(0, kScreenHeight-kDateViewH, kScreenWidth, kScreenHeight-kDateViewH);
    }];
}
- (void)dismiss{
    
    [UIView animateWithDuration:0.3f animations:^{
        self.baseView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight-kDateViewH);
    }completion:^(BOOL finished) {
        self.dimView.hidden = YES;
        self.hidden = YES;
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismiss];
}

#pragma mark - setters
- (void)setTipString:(NSString *)tipString
{
    _tipString = tipString;
    self.titleLabel.text = tipString;
}

#pragma mark - 点击事件
- (void)clickCancelAction:(UIButton *)sender{
    [self dismiss];
}
- (void)clickComfirmAction:(UIButton *)sender{
    [self dismiss];
    
    NSString *date  = [NSDateExtra getDateStringWithDateString:self.selectDateValue currenDateFormat:@"yyyy年MM月dd日" dateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [NSString stringWithFormat:@"%@ %@",date,self.selectAMPM];
    NSLog(@"选择的时间:%@",dateString);
    if (self.comfirmAction) {
        self.comfirmAction(dateString);
    }


}
#pragma mark - getters

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy"];
    }
    return _dateFormatter;
}
- (UIPickerView *)pickView {
    if (!_pickView) {
        _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, kPickViewH)];
        _pickView.backgroundColor = HEX_RGB(@"FFFFFF");
        _pickView.delegate = self;
        _pickView.dataSource = self;
    }
    return _pickView;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, 1)];
        _lineView.backgroundColor = HEX_RGB(@"EEEEEE");;
    }
    return _lineView;
}


- (UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc] init];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:HEX_RGB(@"#A3A3A3") forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = kCustomFont(@"PingFangSC-Medium", 15.0f);
        [_cancelBtn addTarget:self action:@selector(clickCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [[UIButton alloc] init];
        [_confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:HEX_RGB(@"#2384D8") forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = kCustomFont(@"PingFangSC-Medium", 15.0f);
        [_confirmBtn addTarget:self action:@selector(clickComfirmAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel LabelWithFont:kSystemFont(16.0f) titleColor:HEX_RGB(@"333333") textAlignment:ZZTextAlignmentCenter];
    }
    return _titleLabel;
}

- (UIView *)dimView{
    if (!_dimView) {
        _dimView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _dimView.alpha = 0.3;
        _dimView.backgroundColor = [UIColor blackColor];
    }
    return _dimView;
}

- (UIView *)baseView{
    if (!_baseView) {
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kDateViewH)];
        _baseView.backgroundColor = [UIColor whiteColor];
    }
    return _baseView;
}

@end
